package client

import (
	"fmt"
	"github.com/gorilla/websocket"
	"sync"
)

type User struct {
	UserId, ClientId string
	Conn             *websocket.Conn
}

type UserManager interface {
	Set(conn *websocket.Conn, clientId, userId string) error
	Get(userId string) (*websocket.Conn, error)
	Del(clientId string) error
}
type UserClient struct {
	Users     map[string]*User // map[userId]*User
	Mu        sync.RWMutex
	UserGroup map[string]string // map[userId]clientId
}

func NewUserClient() *UserClient {
	return &UserClient{
		Users:     make(map[string]*User),
		UserGroup: make(map[string]string),
	}
}

func (uc *UserClient) Set(conn *websocket.Conn, clientId, userId string) error {
	uc.Mu.Lock()
	defer uc.Mu.Unlock()

	user := &User{
		UserId:   userId,
		ClientId: clientId,
		Conn:     conn,
	}

	uc.Users[userId] = user
	uc.UserGroup[userId] = clientId

	return nil
}

func (uc *UserClient) Get(userId string) (*websocket.Conn, error) {
	uc.Mu.RLock()
	defer uc.Mu.RUnlock()

	user, exists := uc.Users[userId]
	if !exists {
		return nil, fmt.Errorf("user not found for userId: %s", userId)
	}

	return user.Conn, nil
}

func (uc *UserClient) Del(clientId string) error {
	uc.Mu.Lock()
	defer uc.Mu.Unlock()

	for userId, client := range uc.UserGroup {
		if client == clientId {
			delete(uc.Users, userId)
			delete(uc.UserGroup, userId)
			return nil
		}
	}

	return fmt.Errorf("clientId not found: %s", clientId)
}
